package com.team06.dao;

import com.team06.pojo.Ckls;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.sql.PreparedStatement;
import java.sql.Statement;

@Repository
public class CklsDao {
    private static final Logger LOGGER = LoggerFactory.getLogger(CklsDao.class);
    private final JdbcTemplate jdbcTemplate;

    public CklsDao(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    @Transactional
    public void insertMessage(Ckls entity) {
        // 1. 插入主表 MSG_DFME_CKLS
        String mainSql = "INSERT INTO MSG_DFME_CKLS (" +
                "DFLT_FLID, DFLT_FFID, DFLT_FIDE, DFLT_FATT, DFLT_CKLS_FCES, " +
                "DFLT_CKLS_FCEE, DFLT_CKLS_FCRS, DFLT_CKLS_FCRE, DFLT_CKLS_MCES, " +
                "DFLT_CKLS_MCEE, DFLT_CKLS_MCRS, DFLT_CKLS_MCRE, DFLT_CKLS_FCDP, " +
                "DFLT_CKLS_MCDP) " +
                "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

        KeyHolder keyHolder = new GeneratedKeyHolder();

        try {
            // 插入主表
            jdbcTemplate.update(connection -> {
                PreparedStatement ps = connection.prepareStatement(mainSql, Statement.RETURN_GENERATED_KEYS);
                ps.setString(1, entity.getDfltFLID());
                ps.setString(2, entity.getDfltFFID());
                ps.setString(3, entity.getDfltFIDE());
                ps.setString(4, entity.getDfltFATT());
                ps.setString(5, entity.getDfltCklsFces());
                ps.setString(6, entity.getDfltCklsFcee());
                ps.setString(7, entity.getDfltCklsFcrs());
                ps.setString(8, entity.getDfltCklsFcre());
                ps.setString(9, entity.getDfltCklsMces());
                ps.setString(10, entity.getDfltCklsMcee());
                ps.setString(11, entity.getDfltCklsMcrs());
                ps.setString(12, entity.getDfltCklsMcre());
                ps.setString(13, entity.getDfltCklsFcdp());
                ps.setString(14, entity.getDfltCklsMcdp());
                return ps;
            }, keyHolder);

            long mainId = keyHolder.getKey().longValue();
            LOGGER.info("Ckls 主表数据插入成功，ID: {}", mainId);

            // 2. 解析FCDP获取柜台信息（示例：F05-F08）
            String[] counters = entity.getDfltCklsFcdp().split("-");

            // 3. 插入新表 DFME_CKLS_DETAIL
            String detailSql = "INSERT INTO DFME_CKLS_DETAIL (" +
                    "CKLS_ID, CKNO, CODE, CKAT, TYPE, CCAR, ESTR, EEND, RSTR, REND, BTSC) " +
                    "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

            // 为每个柜台插入一条记录
            for (int i = 0; i < counters.length; i++) {
                jdbcTemplate.update(detailSql,
                        mainId,          // CKLS_ID
                        i + 1,           // CKNO 从1开始编号
                        counters[i],      // CODE (如F05)
                        entity.getDfltFATT(), // CKAT 使用航班属性
                        null,             // TYPE
                        null,             // CCAR
                        entity.getDfltCklsFces(), // ESTR
                        entity.getDfltCklsFcee(), // EEND
                        null,             // RSTR
                        null,             // REND
                        "T2"              // BTSC (假设值)
                );
            }

            LOGGER.info("成功插入 {} 条柜台详情记录到 DFME_CKLS_DETAIL", counters.length);

        } catch (Exception e) {
            LOGGER.error("Ckls 数据插入失败", e);
            throw new RuntimeException("Failed to insert Ckls message into database", e);
        }
    }
}